package com.sky.controller.user;

import com.sky.result.Result;
import com.sky.service.UserDishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Autowired
    private UserDishService userDishService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")

    public Result list(@RequestParam Integer categoryId) {
        /**
         * 缓存优化菜品
         * 使用mysql查询前，判断redis缓存中是否存在数据
         */
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String key = "dish_" + categoryId;
        //如果缓存中存在对应数据
        List<DishVO> dishListCache = (List<DishVO>) valueOperations.get(key);
        if (dishListCache != null&& dishListCache.size() > 0) {
            return Result.success(dishListCache);
        }

        List<DishVO> dishList =userDishService.list(categoryId);
        redisTemplate.opsForValue().set(key,dishList);

       return Result.success(dishList);
    }


}
